package com.egoo.ticket.server.service.impl;

import com.egoo.ticket.server.dao.ReportDataDao;
import com.egoo.ticket.server.pojo.dto.ReportDataDto;
import com.egoo.ticket.server.pojo.vo.ReportDataExcelForCustomVo;
import com.egoo.ticket.server.pojo.vo.ReportDataExcelVo;
import com.egoo.ticket.server.pojo.vo.ReportDataVo;
import com.egoo.ticket.server.service.ReportDataService;
import com.egoo.ticket.server.utils.common.DbResponse;
import com.egoo.ticket.server.utils.common.ResponseConstant;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Interval;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author Administrator
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class ReportDataServiceImpl implements ReportDataService {

	@Autowired
	private ReportDataDao reportDataDao;
	/**
	 * TODO 获取报表统计总数
	 * @author: victor_tang
	 * @createtime: 2020/5/25 15:10
	 * @param dto 1
	 * @return: com.egoo.ews.service.pojo.vo.ReportDataVo
	 */
	@Override
	public DbResponse getTotalByCondition(ReportDataDto dto) {
		ReportDataVo reportDataVo = reportDataDao.selectTotalByCondition(dto);
		try {
			reportDataVo = conditionTranslate(reportDataVo);
		} catch (Exception e) {
			e.printStackTrace();
			log.info("完成率和时间转完异常:"+e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"统计失败");
		}
		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,"数量统计成功",reportDataVo);
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 计算完成率 和 平均完成时长
	 * @Param:
	 * @return:
	 * @Date: 2020/5/29
	 */
	private ReportDataVo conditionTranslate(ReportDataVo reportDataVo) {
		Integer createCount = reportDataVo.getCreateCount();
		Integer complateCount = reportDataVo.getComplateCount();
		Integer timeOutComplatedCount = reportDataVo.getTimeOutComplatedCount();
		Integer timeOutCount = reportDataVo.getTimeOutCount();
		Long finishedTimeCount = reportDataVo.getFinishedTimeCount();
		Double finishRate = 0.0;
		if ( createCount != 0){
			finishRate = ((double)complateCount/createCount)*100;
		}

		String detailTime = "0";
		if(complateCount != 0 && finishedTimeCount != null){
			Long averageFinishTimeForOne = (finishedTimeCount / complateCount)*1000;
			detailTime = getDetailTime(averageFinishTimeForOne);
		}
		reportDataVo.setFinishRate(finishRate);
		reportDataVo.setAverageFinishTime(detailTime);
		return reportDataVo;

	}

	/**
	 * @Author: Donny_dong
	 * @Description: 将时间毫秒数转换为具体：天，时，分
	 * @Param:
	 * @return:
	 * @Date: 2020/5/29
	 */
	private String getDetailTime(Long different) {

		long secondsInMilli = 1000;
		long minutesInMilli = secondsInMilli * 60;
		long hoursInMilli = minutesInMilli * 60;
		long daysInMilli = hoursInMilli * 24;

		long elapsedDays = different / daysInMilli;
		different = different % daysInMilli;

		long elapsedHours = different / hoursInMilli;
		different = different % hoursInMilli;

		long elapsedMinutes = different / minutesInMilli;
		different = different % minutesInMilli;

		long elapsedSeconds = different / secondsInMilli;

		String detailTime = elapsedDays+"天"+elapsedHours+"时"+ elapsedMinutes+"分"+ elapsedSeconds+"秒";

		return detailTime;
	}


	/**
	 * TODO 获取详情列表数据
	 * @author: victor_tang
	 * @createtime: 2020/5/25 15:10
	 * @param dto 1
	 * @return: java.utils.List<com.egoo.ews.service.pojo.vo.ReportDataVo>
	 */
	@Override
	public DbResponse getDetailListByCondition(ReportDataDto dto) {
		Integer pageSize = dto.getPageSize();
		Integer page = dto.getPage();
		if (page !=null && pageSize !=null ) {
			page = (dto.getPage()-1)*pageSize;
			dto.setPage(page);
		}

		if (StringUtils.isEmpty(dto.getStartTime()) && StringUtils.isEmpty(dto.getEndTime())){
			String currentDateStr = getCurrentDateStr(dto);
			String createTime = reportDataDao.getCreateTime();
			if (StringUtils.isEmpty(createTime)){
				return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,ResponseConstant.SELECT_SUCCESS_MSG,new ArrayList(),0L);
			}
			dto.setEndTime(currentDateStr);
			dto.setStartTime(createTime);
		}

		Integer days = getDays(dto);
		dto.setDays(days);

		List<ReportDataVo> reportDataVos = reportDataDao.selectDetailListByCondition(dto);
		try {
			if (CollectionUtils.isEmpty(reportDataVos)){
				return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,ResponseConstant.SELECT_SUCCESS_MSG,reportDataVos,0L);
			}

			List<ReportDataVo> collect = reportDataVos.stream().map(reportDataVo -> conditionTranslate(reportDataVo)).collect(Collectors.toList());
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,ResponseConstant.SELECT_SUCCESS_MSG,collect,new Long(days+1));
		} catch (Exception e) {
			e.printStackTrace();
			log.info("完成率和时间转完异常:"+e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,ResponseConstant.SELECT_FAIL_MSG);
		}
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 获取当前时间字符串
	 * @Param:
	 * @return:
	 * @Date: 2020/6/4
	 */
	private String getCurrentDateStr(ReportDataDto dto) {
		Date date = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String endDate = simpleDateFormat.format(date);

		return endDate;
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 获取起始日期对应的时间差（天）
	 * @Param:
	 * @return:
	 * @Date: 2020/5/29
	 */
	private Integer getDays(ReportDataDto dto) {
		String startTime = dto.getStartTime();
		String endTime = dto.getEndTime();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		int days =0;
		try {
			Date start = simpleDateFormat.parse(startTime);
			Date end = simpleDateFormat.parse(endTime);
			Interval interval = new Interval(start.getTime(),end.getTime());
			DateTime startDate = interval.getStart();
			DateTime endDate = interval.getEnd();
			days = Days.daysBetween(startDate, endDate).getDays();
		} catch (ParseException e) {
			e.printStackTrace();
			log.info("日期转天数异常"+e);
			throw new RuntimeException();

		}
		return days;
	}


	/**
	 * @Author: Donny_dong
	 * @Description: 获取客服工单列表
	 * @Param:
	 * @return:
	 * @Date: 2020/6/1
	 */
	@Override
	public DbResponse getCreaterList(ReportDataDto reportDataDto) {
		List<ReportDataVo> reportDataVos = null;
		PageInfo<ReportDataVo> pageInfo = null;
		if (reportDataDto.getPage() != null && reportDataDto.getPageSize() != null) {
			PageHelper.startPage(reportDataDto.getPage(),reportDataDto.getPageSize());
			reportDataVos = reportDataDao.selectCreaterList(reportDataDto);
			pageInfo = new PageInfo<>(reportDataVos);
		} else {
			reportDataVos = reportDataDao.selectCreaterList(reportDataDto);
		}

		try {
			if (CollectionUtils.isEmpty(reportDataVos)){
				return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,ResponseConstant.SELECT_SUCCESS_MSG,reportDataVos,pageInfo == null?0:pageInfo.getTotal());
			}
			List<ReportDataVo> collect = reportDataVos.stream().map(reportDataVo -> conditionTranslate(reportDataVo)).collect(Collectors.toList());
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,ResponseConstant.SELECT_SUCCESS_MSG,collect,pageInfo == null?0:pageInfo.getTotal());
		} catch (Exception e) {
			e.printStackTrace();
			log.info("完成率和时间转换异常");
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,ResponseConstant.SELECT_FAIL_MSG);
		}

	}

	/**
	 * @Author: Donny_dong
	 * @Description: 获取图表数据
	 * @Param:
	 * @return:
	 * @Date: 2020/6/2
	 */
	@Override
	public DbResponse getGraphicsListByCondition(ReportDataDto reportDataDto) {
		DbResponse dbResponse = this.getDetailListByCondition(reportDataDto);
		List<ReportDataVo> reportDataVoList = (List<ReportDataVo>)dbResponse.getData();
		if (CollectionUtils.isEmpty(reportDataVoList)){
			return dbResponse;
		}
			ArrayList<Integer> createCountList = new ArrayList<>();
		ArrayList<Integer> complateCountList = new ArrayList<>();
		ArrayList<Integer> timeOutCountList = new ArrayList<>();
		ArrayList<Integer> timeOutComplateCountList = new ArrayList<>();
		ArrayList<String> xAxisList = new ArrayList<>();
		for (ReportDataVo r:reportDataVoList){
			createCountList.add(r.getCreateCount());
			complateCountList.add(r.getComplateCount());
			timeOutCountList.add(r.getTimeOutCount());
			timeOutComplateCountList.add(r.getTimeOutComplatedCount());
			xAxisList.add(r.getTime());
		}
		Collections.reverse(createCountList);
		Collections.reverse(complateCountList);
		Collections.reverse(timeOutCountList);
		Collections.reverse(timeOutComplateCountList);
		Collections.reverse(xAxisList);
		ReportDataVo reportDataVo = new ReportDataVo();
		reportDataVo.setCreateCountList(createCountList);
		reportDataVo.setComplateCountList(complateCountList);
		reportDataVo.setTimeOutCountList(timeOutCountList);
		reportDataVo.setTimeOutComplatedCountList(timeOutComplateCountList);
		reportDataVo.setXAxisList(xAxisList);

		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,ResponseConstant.SELECT_SUCCESS_MSG,reportDataVo);
	}


	/**
	 * @Author: Donny_dong
	 * @Description: 详情数据导出
	 * @Param:
	 * @return:
	 * @Date: 2020/6/4
	 */
	@Override
	public ArrayList<ReportDataExcelVo> getDetailListForExcel(ReportDataDto reportDataDto) {
		ArrayList<ReportDataExcelVo> reportDataExcelVos = null;
		try {
			DbResponse dbResponse = this.getDetailListByCondition(reportDataDto);
			List<ReportDataVo> reportDataVoList = (List<ReportDataVo>)dbResponse.getData();
			reportDataExcelVos = new ArrayList<>();

			for (ReportDataVo reportDataVo:
				 reportDataVoList) {
				ReportDataExcelVo reportDataExcelVo = new ReportDataExcelVo();
				BeanUtils.copyProperties(reportDataVo,reportDataExcelVo);
				BigDecimal bg = new BigDecimal(reportDataVo.getFinishRate());
				double f = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
				reportDataExcelVo.setFinishRate(f+"%");
				reportDataExcelVos.add(reportDataExcelVo);
			}
		} catch (BeansException e) {
			e.printStackTrace();
			log.info("数据信息获取异常"+e);
		}

		return reportDataExcelVos;
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 客户列表数据导出
	 * @Param:
	 * @return:
	 * @Date: 2020/6/4
	 */
	@Override
	public ArrayList<ReportDataExcelForCustomVo> getcreaterListForExcel(ReportDataDto reportDataDto) {
		ArrayList<ReportDataExcelForCustomVo> reportDataExcelForCustomVos = null;
		try {
			DbResponse dbResponse = this.getCreaterList(reportDataDto);
			List<ReportDataVo> reportDataVoList = (List<ReportDataVo>)dbResponse.getData();
			reportDataExcelForCustomVos = new ArrayList<>();

			for (ReportDataVo reportDataVo:reportDataVoList ) {
				ReportDataExcelForCustomVo reportDataExcelForCustomVo = new ReportDataExcelForCustomVo();
				BeanUtils.copyProperties(reportDataVo,reportDataExcelForCustomVo);
				BigDecimal bg = new BigDecimal(reportDataVo.getFinishRate());
				double f = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
					reportDataExcelForCustomVo.setFinishRate(f+"%");
				reportDataExcelForCustomVos.add(reportDataExcelForCustomVo);
			}
		} catch (BeansException e) {
			log.info("客户列表数据获取异常"+e);
		}
		return reportDataExcelForCustomVos;
	}
}
